const express = require('express');
const fs = require('fs');
const path = require('path');
const { imageSizeFromFile } = require('image-size/fromFile')
const app = express();
const ExifReader = require('exifreader');
const sharp = require('sharp');

// 设置端口
const PORT = process.env.PORT || 6575;

// 设置根目录为 D 盘下的 colddata 文件夹
const panfu = 'D'
const rootPath = 'colddata'
const fullPath = `${panfu}:\\${rootPath}`;

// 静态文件托管
app.use(`/${rootPath}`, express.static(fullPath));
app.use('/', express.static(path.join(__dirname, 'web')));

// 获取文件信息的函数
async function getFileInfo(filePath) {
    const stats = fs.statSync(filePath);
    const isDirectory = stats.isDirectory();
    
    // 获取文件的相对路径
    const relativePath = path.relative(fullPath, filePath);
    // 构建静态访问URL
    const url = `/${rootPath}/${relativePath.replace(/\\/g, '/')}`;    
    
    // 检查是否为图片文件
    const ext = path.extname(filePath).toLowerCase();
    const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'];
    const videoExts = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv'];
    const audioExts = ['.mp3', '.wav', '.ogg', '.m4a', '.aac', '.flac'];
    const isPic = !isDirectory && imageExts.includes(ext);
    const isVideo = !isDirectory && videoExts.includes(ext);
    const isAudio = !isDirectory && audioExts.includes(ext);
    
    let dimensions = null;
    let shootTime = null;
    let thumbnailUrl = null;
    
    if (isPic) {
        try {
            dimensions = await imageSizeFromFile(filePath);
            // 生成缩略图
            const thumbnailDir = path.join(__dirname, 'thumbnails');
            if (!fs.existsSync(thumbnailDir)) {
                fs.mkdirSync(thumbnailDir);
            }
            const thumbnailPath = path.join(thumbnailDir, `thumb_${path.basename(filePath)}`);
            // 如果缩略图不存在，则生成
            if (!fs.existsSync(thumbnailPath)) {
                await sharp(filePath)
                    .resize(200, 200, { fit: 'inside' })
                    .jpeg({ quality: 80 })
                    .toFile(thumbnailPath);
            }
            thumbnailUrl = `/thumbnails/thumb_${path.basename(filePath)}`;
            
            // 尝试读取 EXIF 数据
            const tags = await ExifReader.load(filePath);
            if (tags.DateTimeOriginal) {
                const originalDate = tags.DateTimeOriginal.description;
                standardTime = new Date(originalDate.replace(":", "-").replace(":", "-"));
                shootTime = new Date(standardTime.getTime() + (8 * 60 * 60 * 1000))
            }
        } catch (err) {
            console.error(`无法读取图片信息: ${filePath}`, err);
        }
    }
    
    return {
        name: path.basename(filePath),
        size: isDirectory ? null : stats.size,
        isDirectory: isDirectory,
        isPic: isPic,
        isVideo: isVideo,
        isAudio: isAudio,
        url: url,
        thumbnailUrl: thumbnailUrl, // 添加缩略图URL
        width: dimensions ? dimensions.width : null,
        height: dimensions ? dimensions.height : null,
        createTime: new Date(stats.birthtime.getTime() + (8 * 60 * 60 * 1000)),
        shootTime
    };
}

// 获取目录下所有文件信息的函数
async function getAllFiles(dirPath, page) {
    const files = fs.readdirSync(dirPath);
    const start = (page - 1) * 100;
    const end = page * 100;
    const filteredFiles = files.slice(start, end);
    const promises = filteredFiles.map(file => {
        const fullPath = path.join(dirPath, file);
        return getFileInfo(fullPath);
    });
    return Promise.all(promises);
}

// API路由
app.get('/api/photos', async (req, res) => {
    try {
        const dirPath = req.query.path || fullPath;
        const page = req.query.page;
        const absolutePath = dirPath === fullPath ? dirPath : path.join(`${panfu}:`, dirPath);
        
        // 检查目录是否存在
        if (!fs.existsSync(absolutePath)) {
            return res.status(404).json({ error: '目录不存在' });
        }
        
        // 获取所有文件信息
        const filesInfo = await getAllFiles(absolutePath, page);
        res.json(filesInfo);
    } catch (error) {
        console.error('获取文件信息时出错:', error);
        res.status(500).json({ error: '服务器错误' });
    }
});

// 添加缩略图静态文件托管
app.use('/thumbnails', express.static(path.join(__dirname, 'thumbnails')));

// 处理所有其他路由，支持前端 history 模式
app.get('*', (req, res) => {
    // 排除 API 路由和静态资源
    if (!req.path.startsWith('/api') && !req.path.startsWith(`/${rootPath}`)) {
        res.sendFile(path.join(__dirname, 'web', 'index.html'));
    }
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});

// 添加 express.json 中间件来解析 POST 请求的 JSON 数据
app.use(express.json());

// 删除文件或文件夹的函数
async function deleteFileOrDirectory(url) {
    // 从 URL 获取相对路径
    const relativePath = url.replace(`/${rootPath}/`, '').replace(/\//g, '\\');
    const absolutePath = path.join(fullPath, relativePath);
    
    try {
        const stats = fs.statSync(absolutePath);
        if (stats.isDirectory()) {
            fs.rmdirSync(absolutePath, { recursive: true });
        } else {
            fs.unlinkSync(absolutePath);
        }
        return true;
    } catch (error) {
        console.error(`删除失败: ${absolutePath}`, error);
        return false;
    }
}

// 删除文件的 API 路由
app.post('/api/delItems', async (req, res) => {
    try {
        const { urls } = req.body;
        
        if (!Array.isArray(urls)) {
            return res.status(400).json({ error: '参数错误：urls 必须是数组' });
        }
        
        const results = await Promise.all(urls.map(async url => {
            const success = await deleteFileOrDirectory(url);
            return {
                url,
                success
            };
        }));
        
        res.json({
            success: true,
            results
        });
    } catch (error) {
        console.error('删除文件时出错:', error);
        res.status(500).json({ error: '服务器错误' });
    }
});
